package com.zwd.cases.utils.ftp2;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.Properties;

/**
 * @Description 连接ftp服务
 * @Author zhengwd
 * @Date 2022/7/21 9:35
 **/
@Slf4j
public class FtpClient {

    private static String hostName = "10.27.106.20";
    private static Integer port = 21;
    private static String userName = "zwd2315";
    private static String password = "zwd2315";

    private static FTPClient ftpClient;

    public static FTPClient getFTPConnection() {
        ftpClient = new FTPClient();
        try {
            // 连接
            ftpClient.connect(hostName, port);
            // 设置编码
            ftpClient.setControlEncoding("UTF-8");
            // 设置传输文件类型
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 登录
            ftpClient.login(userName, password);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("==============未连接到FTP，用户名或密码错误=================");
                // 拒绝连接
                ftpClient.disconnect();
            } else {
                log.info("==============连接到FTP成功=================");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            log.info("==============FTP的IP地址错误==============");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("==============FTP的端口错误==============");
        }
        return ftpClient;
    }

    public static void closeConnect() {
        log.warn("关闭ftp服务器");
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

